/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: MyAssetPresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.presenter;

import android.text.TextUtils;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.AppUI;
import io.bhex.app.trade.ui.HistoryOptionDeliveryActivity;
import io.bhex.baselib.mvp.BaseFragmentPresenter;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.account.bean.FindPasswordCheckRequest;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.finance.FinanceApi;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.OptionCoinPairBean;
import io.bhex.sdk.quote.bean.QuoteTokensBean;
import io.bhex.sdk.socket.NetWorkObserver;
import io.bhex.sdk.trade.AssetApi;
import io.bhex.sdk.trade.OptionApi;
import io.bhex.sdk.trade.TradeApi;
import io.bhex.sdk.trade.bean.AssetListResponse;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BasePresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.UISafeKeeper;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.trade.bean.CoinplusAssetResponse;
import io.bhex.sdk.trade.bean.FuturesAssetListResponse;
import io.bhex.sdk.trade.bean.OpenOrderResponse;
import io.bhex.sdk.trade.bean.OptionAssetListResponse;
import io.bhex.sdk.trade.bean.OptionHoldOrderResponse;
import io.bhex.sdk.trade.bean.OrderBean;
import io.bhex.sdk.trade.futures.FuturesApi;

import static io.bhex.baselib.constant.AppData.HIDE_MIN_BTC;

/**
 * ================================================
 * 描   述：我的资产
 * ================================================
 */

public class MyAssetPresenter extends BaseFragmentPresenter<MyAssetPresenter.MyAssetUI> {

    private FuturesAssetListResponse mFuturesAssetListResponse;

    public interface MyAssetUI extends AppUI{
        //void showAsset(AssetListResponse response);

        void AssetChange();

        void showAssetList(List<AssetListResponse.BalanceBean> tokenList);

        void showOptionAssetList(List<OptionAssetListResponse.OptionAssetBean> tokenList);

        void showOptionHoldOrders(List<OptionHoldOrderResponse.OptionHoldOrderBean> tokenList);

        void showCoinPlusLists(List<CoinplusAssetResponse.CoinplusItemBean> tokenList);

        void refreshAssetComplete();

        void showFuturesAssetList(List<FuturesAssetListResponse.FuturesAssetBean> futuresTokenList);
    }

    LinkedHashMap<String,AssetListResponse.BalanceBean> tokenMap = new LinkedHashMap<String,AssetListResponse.BalanceBean>();
    LinkedHashMap<String,FuturesAssetListResponse.FuturesAssetBean> futuresTokenMap = new LinkedHashMap<String,FuturesAssetListResponse.FuturesAssetBean>();
    LinkedHashMap<String,OptionAssetListResponse.OptionAssetBean> optionTokenMap = new LinkedHashMap<String,OptionAssetListResponse.OptionAssetBean>();
    LinkedHashMap<String,OptionHoldOrderResponse.OptionHoldOrderBean> optionHoldOrderMap = new LinkedHashMap<String,OptionHoldOrderResponse.OptionHoldOrderBean>();
    List<AssetListResponse.BalanceBean> tokenList = new ArrayList<>();
    List<FuturesAssetListResponse.FuturesAssetBean>  futuresTokenList= new ArrayList<>();
    List<OptionAssetListResponse.OptionAssetBean>  optionTokenList= new ArrayList<>();
    List<OptionHoldOrderResponse.OptionHoldOrderBean>  optionHoldOrderList= new ArrayList<>();
    List<CoinplusAssetResponse.CoinplusItemBean>  coinplusList= new ArrayList<>();

    List<AssetListResponse.BalanceBean> filterList = new ArrayList<>();
    AssetListResponse mAssetListResponse;
    OptionAssetListResponse mOptionAssetListResponse;
    OptionHoldOrderResponse mOptionHoldOrderListResponse;
    CoinplusAssetResponse mCoinplusAssetResponse;

    @Override
    public void onUIReady(BaseCoreActivity activity, MyAssetUI ui) {
        super.onUIReady(activity, ui);

//        if (UserInfo.isLogin()) {
//            if (!NetWorkStatus.isConnected(getActivity())) {
//                ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
//                return;
//            }
//            getQuoteTokens();
//            getOptionAssetList();
//            getFuturesAssetList();
//            getOptionHoldOrderList();
//            getCoinPlusAssetList();

            loadFuturesAssetTokens();
//        }
    }

    /**
     * 加载期货数据
     */
    private void loadFuturesAssetTokens() {
        List<String> futuresCoinTokens = SymbolDataManager.GetInstance().getFuturesCoinToken();
        if (futuresCoinTokens != null && futuresCoinTokens.size()>0) {
            for (String futuresCoinToken : futuresCoinTokens) {
                FuturesAssetListResponse.FuturesAssetBean futuresAssetBean = new FuturesAssetListResponse.FuturesAssetBean();
                futuresAssetBean.tokenId = futuresCoinToken;
                futuresAssetBean.tokenName = futuresCoinToken;
                futuresAssetBean.availableMargin = "";
                futuresAssetBean.orderMargin = "";
                futuresAssetBean.positionMargin = "";
                futuresAssetBean.total = "";
                futuresTokenMap.put(futuresCoinToken,futuresAssetBean);
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 搜索
     * @param searchContent
     * @param isFilterZero
     */
    public void search(String searchContent, boolean isFilterZero) {
        if (!tokenList.isEmpty()) {
            filterList.clear();
            for (AssetListResponse.BalanceBean BalanceBean : tokenList) {

                if (isMatch(BalanceBean,searchContent,isFilterZero)) {
                    filterList.add(BalanceBean);
                }
            }
            getUI().showAssetList(filterList);

        }
    }

    private boolean isMatch(AssetListResponse.BalanceBean balanceBean, String searchContent, boolean isFilterZero) {
        try{
            if (!TextUtils.isEmpty(searchContent)) {
                String token = balanceBean.getTokenId();
                String tokenName = balanceBean.getTokenName();
                if (!token.contains(searchContent)&&!token.contains(searchContent.toUpperCase()) && !tokenName.contains(searchContent) && !tokenName.contains(searchContent.toUpperCase())) {
                    return false;
                }
            }
            if (isFilterZero) {
                String total = balanceBean.getBtcValue();
                if (!TextUtils.isEmpty(total)) {
                    double totald = Double.valueOf(total);
                    if (totald <= HIDE_MIN_BTC){
                        return false;
                    }
                }
                else
                    return false;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return true;
    }

    /**
     * 获取资产列表
     */
    public void getAssetList() {
        TradeApi.SubBalanceData(new NetWorkObserver<List<AssetListResponse.BalanceBean>>(){

            @Override
            public void onShowUI(List<AssetListResponse.BalanceBean> response) {
                if(response != null){
                    addBalanceInfoList(response);
                }
            }

            @Override
            public void onError(String response) {

            }
        });

        TradeApi.RequestBalanceData( new SimpleResponseListener<AssetListResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                //getUI().refreshAssetComplete();
            }

            @Override
            public void onSuccess(AssetListResponse response) {
                super.onSuccess(response);
                showAsset(response);
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }

        });

    }

    /**
     * 获取资产列表
     */
    public void getFuturesAssetList() {
        futuresTokenMap.clear();
        loadFuturesAssetTokens();//重新加载token
        FuturesApi.SubFuturesBalanceData(new NetWorkObserver<List<FuturesAssetListResponse.FuturesAssetBean>>(){

            @Override
            public void onShowUI(List<FuturesAssetListResponse.FuturesAssetBean> response) {
                if(response != null){
                    addFuturesBalanceInfoList(response);
                }
            }

            @Override
            public void onError(String response) {

            }
        });

        FuturesApi.RequestFuturesBalanceData( new SimpleResponseListener<FuturesAssetListResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                //getUI().refreshAssetComplete();
            }

            @Override
            public void onSuccess(FuturesAssetListResponse response) {
                super.onSuccess(response);
                showFuturesAsset(response);
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }

        });

    }

    /**
     * 获取资产列表
     */
    public void getOptionAssetList() {
        OptionApi.SubOptionBalanceData(new NetWorkObserver<List<OptionAssetListResponse.OptionAssetBean>>(){

            @Override
            public void onShowUI(List<OptionAssetListResponse.OptionAssetBean> response) {
                if(response != null){
                    addOptionBalanceInfoList(response);
                }
            }

            @Override
            public void onError(String response) {

            }
        });

        OptionApi.RequestOptionBalanceData( new SimpleResponseListener<OptionAssetListResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                //getUI().refreshAssetComplete();
            }

            @Override
            public void onSuccess(OptionAssetListResponse response) {
                super.onSuccess(response);
                showOptionAsset(response);
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }

        });

    }

    public void getOptionHoldOrderList() {

        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }

        OptionApi.SubOptionHoldOrderChange(new SimpleResponseListener<OptionHoldOrderResponse>() {
            @Override
            public void onSuccess(OptionHoldOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    optionHoldOrderList = response.array;
                    if (optionHoldOrderList != null) {
                        addOptionHoldOrderList(optionHoldOrderList);
                    }
                }
            }
        });

        OptionApi.RequestOptionHoldOrder("", "", new SimpleResponseListener<OptionHoldOrderResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OptionHoldOrderResponse response) {
                super.onSuccess(response);
                showOptionHoldOrder(response);
            }

        });

    }

    private void showAsset(AssetListResponse response){

        if (CodeUtils.isSuccessAutoLogin(getActivity(),response, true, AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
            mAssetListResponse = response;
            addBalanceInfoList(mAssetListResponse.getBalance());
        }
    }

    private void showOptionAsset(OptionAssetListResponse response){

        if (CodeUtils.isSuccessAutoLogin(getActivity(),response, true, AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
            mOptionAssetListResponse = response;
            addOptionBalanceInfoList(mOptionAssetListResponse.array);
        }
    }

    private void showFuturesAsset(FuturesAssetListResponse response){

        if (CodeUtils.isSuccessAutoLogin(getActivity(),response, true, AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
            mFuturesAssetListResponse = response;
            addFuturesBalanceInfoList(mFuturesAssetListResponse.array);
        }
    }

    private void showOptionHoldOrder(OptionHoldOrderResponse response){

        if(response != null && response.array != null) {
            mOptionHoldOrderListResponse = response;
            addOptionHoldOrderList(mOptionHoldOrderListResponse.array);
        }

    }

    private void addBalanceInfoList(List<AssetListResponse.BalanceBean> balanceInfoList){
        if (mAssetListResponse != null && balanceInfoList != null) {
            for (AssetListResponse.BalanceBean balanceBean : balanceInfoList) {
                String token = balanceBean.getTokenId();
                AssetListResponse.BalanceBean itemBean = tokenMap.get(token);
                if (itemBean != null) {
                    //此处币Icon赋值，方便传递到下一页
                    balanceBean.setIconUrl(itemBean.getIconUrl());
                    balanceBean.setTokenFullName(itemBean.getTokenFullName());
                    balanceBean.setAllowWithdraw(itemBean.isAllowWithdraw());
                    balanceBean.setAllowDeposit(itemBean.isAllowDeposit());
                    balanceBean.setNeedAddressTag(itemBean.isNeedAddressTag());
                    tokenMap.put(token, balanceBean);
                }
            }

            tokenList.clear();
            BigDecimal totalBtcValue = new BigDecimal("0");
            for (String key : tokenMap.keySet()) {
                AssetListResponse.BalanceBean balanceBean = tokenMap.get(key);
                tokenList.add(balanceBean);

                String btcValue = balanceBean.getBtcValue();
                if (!TextUtils.isEmpty(btcValue)) {
                    totalBtcValue = totalBtcValue.add(new BigDecimal(btcValue));
                }
            }
            mAssetListResponse.setBtcValue(totalBtcValue.toPlainString());
            mAssetListResponse.setBalance(tokenList);
            //getUI().showAsset(mAssetListResponse);
            getUI().showAssetList(tokenList);
            getUI().AssetChange();
        }
    }

    private void addOptionBalanceInfoList(List<OptionAssetListResponse.OptionAssetBean> balanceInfoList){
        if (mOptionAssetListResponse != null && balanceInfoList != null) {
            for (OptionAssetListResponse.OptionAssetBean balanceBean : balanceInfoList) {
                String token = balanceBean.tokenId;
                //OptionAssetListResponse.OptionAssetBean itemBean = optionTokenMap.get(token);
                optionTokenMap.put(token, balanceBean);
            }

            optionTokenList.clear();
            for (String key : optionTokenMap.keySet()) {
                OptionAssetListResponse.OptionAssetBean balanceBean = optionTokenMap.get(key);
                optionTokenList.add(balanceBean);
            }
            //getUI().showAsset(mAssetListResponse);
            getUI().AssetChange();
            getUI().showOptionAssetList(optionTokenList);
        }
    }

    private void addFuturesBalanceInfoList(List<FuturesAssetListResponse.FuturesAssetBean> balanceInfoList){
        if (mFuturesAssetListResponse != null && balanceInfoList != null) {
            for (FuturesAssetListResponse.FuturesAssetBean balanceBean : balanceInfoList) {
                String token = balanceBean.tokenId;
                //OptionAssetListResponse.OptionAssetBean itemBean = optionTokenMap.get(token);
                futuresTokenMap.put(token, balanceBean);
            }

            futuresTokenList.clear();
            for (String key : futuresTokenMap.keySet()) {
                FuturesAssetListResponse.FuturesAssetBean balanceBean = futuresTokenMap.get(key);
                futuresTokenList.add(balanceBean);
            }
            //getUI().showAsset(mAssetListResponse);
            getUI().AssetChange();
            getUI().showFuturesAssetList(futuresTokenList);
        }
    }

    private void addOptionHoldOrderList(List<OptionHoldOrderResponse.OptionHoldOrderBean> holdOrderList){
        if (holdOrderList != null) {
            optionHoldOrderMap.clear();
            for (OptionHoldOrderResponse.OptionHoldOrderBean balanceBean : holdOrderList) {
                String balanceId = balanceBean.balanceId;
                //OptionHoldOrderResponse.OptionHoldOrderBean itemBean = optionHoldOrderMap.get(balanceId);
                optionHoldOrderMap.put(balanceId, balanceBean);
            }

            optionHoldOrderList.clear();
            for (String key : optionHoldOrderMap.keySet()) {
                OptionHoldOrderResponse.OptionHoldOrderBean balanceBean = optionHoldOrderMap.get(key);
                optionHoldOrderList.add(balanceBean);
            }
            //getUI().showAsset(mAssetListResponse);
            //getUI().AssetChange();
            getUI().showOptionHoldOrders(optionHoldOrderList);
        }
    }

    /**
     * 获取报价Token集合
     */
    public void getQuoteTokens() {
        AssetApi.RequestQuoteTokens(UISafeKeeper.guard(getUI(),new SimpleResponseListener<List<QuoteTokensBean.TokenItem>>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(List<QuoteTokensBean.TokenItem> response) {
                super.onSuccess(response);
                    List<QuoteTokensBean.TokenItem> datas = response;
                    tokenMap.clear();
                    if (datas != null) {
                        for (QuoteTokensBean.TokenItem data : datas) {
                            AssetListResponse.BalanceBean BalanceBean = new AssetListResponse.BalanceBean();
                            BalanceBean.setTokenId(data.getTokenId());
                            BalanceBean.setTokenName(data.getTokenName());
                            BalanceBean.setTokenFullName(data.getTokenFullName());
                            BalanceBean.setTotal("0.00");
                            BalanceBean.setIconUrl(data.getIconUrl());
                            BalanceBean.setAllowDeposit(data.isAllowDeposit());
                            BalanceBean.setAllowWithdraw(data.isAllowWithdraw());
                            BalanceBean.setNeedAddressTag(data.isNeedAddressTag());
                            tokenMap.put(data.getTokenId(),BalanceBean);
                        }
                        getAssetList();


                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        }));
    }


    public void getCoinPlusAssetList() {
        FinanceApi.getFinanceAssetList(UISafeKeeper.guard(getUI(),new SimpleResponseListener<CoinplusAssetResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(CoinplusAssetResponse response) {
                super.onSuccess(response);
                if(response != null && response.balanceInfoList != null) {
                    mCoinplusAssetResponse = response;
                    coinplusList = response.balanceInfoList;
                    getUI().showCoinPlusLists(coinplusList);
                }

            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        }));
    }

    public void RequestOptionSymbols(final String symbolId) {
        if (!NetWorkStatus.isConnected(getActivity()) ){
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            return;
        }


        OptionApi.RequestOptionSymbols(symbolId, new SimpleResponseListener<OptionCoinPairBean>() {
            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }
            @Override
            public void onSuccess(OptionCoinPairBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<CoinPairBean>  data = response.array;
                    if (data != null) {
                        for (CoinPairBean bean:data) {
                            if(bean != null && !TextUtils.isEmpty(symbolId) && symbolId.equalsIgnoreCase(bean.getSymbolId())){
                                bean.setBuyMode(true);
                                bean.setNeedSwitchTradeTab(true);
                                getActivity().finish();
                                EventBus.getDefault().postSticky(bean);
                                return;
                            }
                        }
                    }
                }
                ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            }
        });
    }
}
